package com.lzh.common.aliyun;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.green20220302.Client;
import com.aliyun.green20220302.models.ImageModerationRequest;
import com.aliyun.green20220302.models.ImageModerationResponse;
import com.aliyun.green20220302.models.ImageModerationResponseBody;
import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.CannedAccessControlList;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.teautil.models.RuntimeOptions;

import lombok.Getter;
import lombok.Setter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.io.ByteArrayInputStream;
import java.util.*;

@Getter
@Setter
@Component
@ConfigurationProperties(prefix = "aliyun")
public class GreenImageScan {

    private String accessKeyId = "LTAI5t683otz7N2jwiyBP4Ps" ;
    private String secret = "YQ4UnxyLLgHOjDCdrWQEocu4bHKVNc" ;
    private String OssEndPoint = "oss-cn-shanghai.aliyuncs.com";
    private String GreenEndPoint = "green-cip.cn-shanghai.aliyuncs.com" ;

    public Map imageScan(List<byte[]> imageList) throws Exception {
        Map end = new HashMap() ;
        for (byte[] res : imageList) {
            // 填写Bucket名称
            String bucketName = "leadnewsss";
            // 填写Object完整路径（文件名）
            String objectName = UUID.randomUUID() + ".jpg";
            // 创建OSSClient实例。
            OSS ossClient = new OSSClientBuilder().build(OssEndPoint, accessKeyId, secret);

            try {
                //            ossClient.setBucketAcl(bucketName, CannedAccessControlList.Private);
                // 创建PutObjectRequest对象。
                PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, new ByteArrayInputStream(res));

                // 创建PutObject请求。
                PutObjectResult result = ossClient.putObject(putObjectRequest);
            } catch (OSSException oe) {
                System.out.println("Caught an OSSException, which means your request made it to OSS, "
                        + "but was rejected with an error response for some reason.");
                System.out.println("Error Message:" + oe.getErrorMessage());
                System.out.println("Error Code:" + oe.getErrorCode());
                System.out.println("Request ID:" + oe.getRequestId());
                System.out.println("Host ID:" + oe.getHostId());
            } catch (ClientException ce) {
                System.out.println("Caught an ClientException, which means the client encountered "
                        + "a serious internal problem while trying to communicate with OSS, "
                        + "such as not being able to access the network.");
                System.out.println("Error Message:" + ce.getMessage());
            } finally {
                if (ossClient != null) {
                    ossClient.shutdown();
                }
            }
            Map <String,String> now = new HashMap();
            now = check(bucketName, objectName) ;
            if( "block".equals(now.get("suggestion"))){
                return now ;
            }
        }
        end.put("suggestion","pass");
        return end ;
    }

    // 开始审核图片
    private Map check(String bucketName, String objectName) throws Exception {
        // 返回参数Map
        Map<String, String> resultMap = new HashMap<>();

        ImageModerationResponse response = invokeFunction(accessKeyId, secret, GreenEndPoint, bucketName, objectName);
//        System.out.println(response.getStatusCode().toString());
//        System.out.println(response.getHeaders().toString());
//        System.out.println(response.getBody().getData());
//        System.out.println(response.getBody().getMsg());
//        System.out.println("---------------------");
        try {
            if (response != null) {
                if (response.getStatusCode() == 200) {
                    ImageModerationResponseBody body = response.getBody();
                    System.out.println("requestId=" + body.getRequestId());
                    System.out.println("code=" + body.getCode());
                    System.out.println("msg=" + body.getMsg());
                    if (body.getCode() == 200) {
                        ImageModerationResponseBody.ImageModerationResponseBodyData data = body.getData();
                        System.out.println("dataId=" + data.getDataId());
                        List<ImageModerationResponseBody.ImageModerationResponseBodyDataResult> results = data.getResult();
                        for (ImageModerationResponseBody.ImageModerationResponseBodyDataResult result : results) {
                            System.out.println("label=" + result.getLabel());
                            System.out.println("confidence=" + result.getConfidence());
                            String label = result.getLabel();
                            if (label.equals("nonLabel")) {
                                resultMap.put("suggestion", "pass");
                            } else {
                                resultMap.put("suggestion", "block");
                                resultMap.put("label", label);
                            }
                        }
                    } else {
                        System.out.println("image moderation not success. code:" + body.getCode());
                    }
                } else {
                    System.out.println("response not success. status:" + response.getStatusCode());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return resultMap;
    }

    private ImageModerationResponse invokeFunction(String accessKeyId, String secret, String GreenEndPoint, String bucketName, String objectName) throws Exception {
        //注意，此处实例化的client请尽可能重复使用，避免重复建立连接，提升检测性能。
        Client client = createClient(accessKeyId, secret, GreenEndPoint);
        // 创建RuntimeObject实例并设置运行参数
        RuntimeOptions runtime = new RuntimeOptions();
        // 检测参数构造。
        Map<String, String> serviceParameters = new HashMap<>();
        //待检测数据唯一标识
        serviceParameters.put("dataId", UUID.randomUUID().toString());
        // 待检测文件所在bucket的区域。
        serviceParameters.put("ossRegionId", "oss-cn-shanghai");
        // 待检测文件所在bucket名称。示例：bucket001
        serviceParameters.put("ossBucketName", bucketName);
        // 待检测文件。 示例：image/001.jpg
        serviceParameters.put("ossObjectName", objectName);

        ImageModerationRequest request = new ImageModerationRequest();
        // 图片检测service：内容安全控制台图片增强版规则配置的serviceCode，示例：baselineCheck
        // 支持service请参考：https://help.aliyun.com/document_detail/467826.html?0#p-23b-o19-gff
        request.setService("baselineCheck");
        request.setServiceParameters(JSON.toJSONString(serviceParameters));

        ImageModerationResponse response = null;
        try {
            response = client.imageModerationWithOptions(request, runtime);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return response;
    }

    private Client createClient(String accessKeyId, String accessKeySecret, String GreenEndPoint) throws Exception {
        Config config = new Config();
        config.setAccessKeyId(accessKeyId);
        config.setAccessKeySecret(accessKeySecret);
        config.setEndpoint(GreenEndPoint);
        return new Client(config);
    }
}
